package com.stepshop.wechat.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpRequest;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.stepshop.core.annotation.ActionToken;
import com.stepshop.wechat.entity.MsgValueColor;
import com.stepshop.wechat.factory.MsgSendFactory;
import com.stepshop.wechat.msg.MsgSend;
import com.stepshop.wechat.utils.HttpClientUtil;
import com.stepshop.wechat.utils.MD5Util;
import com.stepshop.wechat.utils.MsgSendUtil;
import com.stepshop.wechat.utils.Signature;
import com.stepshop.wechat.utils.TwoDimensionCodeUtil;
import com.stepshop.wechat.utils.XMLUtil;

@Controller
@RequestMapping("/scanCode")
public class ScanCodeController{
	private Logger logger=Logger.getLogger(this.getClass());
	@RequestMapping("/getCode")
	@ActionToken
	public void getCode(HttpServletRequest request,HttpServletResponse response){
		try {
			logger.info("ip:["+request.getRemoteAddr()+"]["+request.getRemoteHost()+"]["+request.getRemoteUser()+"]["+request.getHeader("x-forwarded-for")+"]");
			HttpClientUtil httpClientUtil = new HttpClientUtil();
			String tokenJson=httpClientUtil.doPost("http://wechat-pre.0071515.com/pangu-wechat/dimenCode/getToken.do?valid=iiudihfeqpxkegEl4dkiR4SKd","", "UTF-8");
			JSONObject jsonObject = JSON.parseObject(tokenJson);
			String token=jsonObject.getString("token");
//			String token="-ITkcPvjEuahROor7HN2Ia8lNQD09ueMcYcD_MaWbXdT_ruXx2ruLFNOCIhbAarOx3l8MwjnD9jbhr9KzCCMWZYPvyUk20VcXGH6neJL2E4RFRhAIAKYK";
			String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token="
					+ token;
//			String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token="
//					+ token;
			String json="";
			Map<String,Object> codeMap=new HashMap<String,Object>();
			Map<String,Object> actionInfoMap=new HashMap<String, Object>();
			Map<String,Object> sceneMap=new HashMap<String, Object>();
			codeMap.put("action_name", "QR_SCENE");
			codeMap.put("expire_seconds", "604800");
			String timeMillis = System.currentTimeMillis()+"";
			sceneMap.put("scene_id","233442");
			sceneMap.put("scene_str", "bbbb");
			actionInfoMap.put("scene", sceneMap);
			codeMap.put("action_info", actionInfoMap);
			json=JSON.toJSONString(codeMap);
			System.out.println(json);
			String codeJson = httpClientUtil.doPost(url,json,"UTF-8");
			Map codeInfo = JSON.parseObject(codeJson, Map.class);
			System.out.println(codeInfo);
			response.setHeader("content-disposition", "attachment;filename="+new Date().getTime()+".png");
			// 直接同腾讯得到图片
			InputStream in = httpClientUtil.doGet("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket="+codeInfo.get("ticket"), "UTF-8");
			ServletOutputStream outputStream = response.getOutputStream();
			TwoDimensionCodeUtil dimenUtil=new TwoDimensionCodeUtil();
//			byte[] by=new byte[1024];
//			int len=0;
//			while((len=in.read(by))!=-1){
//				outputStream.write(by, 0, len);
//			}
//			in.close();
			String imgUrl = (String) codeInfo.get("url");
			System.out.println(imgUrl);
//			ServletOutputStream outputStream = response.getOutputStream();
//			TwoDimensionCodeUtil dimenUtil=new TwoDimensionCodeUtil();
			dimenUtil.encoderQRCode(imgUrl, outputStream);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	@RequestMapping("/getIndustryInfo")
	@ResponseBody
	public String getIndustryInfo(@RequestParam("token")String token,HttpServletRequest request,HttpServletResponse response){
		String url="http://www.baidu.com";
		String temid="SRhyPeusD84sjARrBB0Ppbjp0mC7FmyYrIbWM4r1fRE";
		String openid="owaqXxAVN9MlSgIwBeyLl7fiR1IA";
//		MsgSend msgSend = MsgSendFactory.getMsgSend("com.stepshop.wechat.msg.ScanMsgSend");
		Map<String,MsgValueColor> dataMap=new HashMap<String,MsgValueColor>();
		dataMap.put("fee", new MsgValueColor("5288","#ff0000"));
		dataMap.put("first", new MsgValueColor("您已经支付成功"));
		dataMap.put("name", new MsgValueColor("神州八号"));
		dataMap.put("remark", new MsgValueColor("订单已经进库,我们会及时安排发货"));
		MsgSendUtil.send(dataMap,url,temid,openid);
		return null;
	}
	@RequestMapping("/dimenImage")
	public void dimenImage(HttpServletRequest request,HttpServletResponse response){
		try {
			//1,处理xml文档
			//map -->xml
			Map<String,String> paramMaps=new TreeMap<String, String>();
			paramMaps.put("appid","wxd152167cedf23e16");
			paramMaps.put("mch_id", "1324751901");
			//随机字符串 不长于32位  (后台生成)
			paramMaps.put("nonce_str",MD5Util.MD5Encode(new Date().getTime()+"","UTF-8") );
			//attach   附加数据，在查询API和支付通知中原样返回，该字段主要用于商户携带订单的自定义数据
			paramMaps.put("attach", "神工007支付");
			//商品描述  商品或支付单简要描述
			paramMaps.put("body", "神工007-"+"支付测试");
			//商户订单号  商户系统内部的订单号,32个字符内、可包含字母, 其他说明见商户订单号
			//传参过来   pay_id
			paramMaps.put("out_trade_no",new Date().getTime()+"");
			//总金额 订单总金额，单位为分，详见支付金额
			String feeSum="1";
			//当前不在浏览器打开且是开发模式/测试模式，默认为一分钱
			paramMaps.put("total_fee",feeSum);
			//终端IP  APP和网页支付提交用户端ip，Native支付填调用微信支付API的机器IP
			// 用户ip
			paramMaps.put("spbill_create_ip", "219.239.57.162");
			//通知地址 	接收微信支付异步通知回调地址，通知url必须为直接可访问的url，不能携带参数。  FIXME  上生产库 回调地址需要修改
			// 是否前台传入待定
			String notifyUrl="www.baidu.com";
			paramMaps.put("notify_url",notifyUrl);
			//720187
			//交易类型 JSAPI  
			paramMaps.put("trade_type", "NATIVE");
			//获得签名
			String sign = Signature.getSign(paramMaps);
			paramMaps.put("sign",sign);
			//2,发送post-- https 请求 获得返回参数
			//预备发送的xml文档 
			String xmlToPost= XMLUtil.map2Xml(paramMaps,"xml");
			logger.info("开始发送请求,请求内容为"+xmlToPost);
			HttpClientUtil httpClientUtil = new HttpClientUtil();
			String url="https://api.mch.weixin.qq.com/pay/unifiedorder";
			String callBackXml = httpClientUtil.doPost(url, xmlToPost,"UTF-8");
			Map callBackMap=new HashMap();
			// 解析callbackXml
			callBackMap = XMLUtil.doXMLParse(callBackXml);
			String returnCode = (String) callBackMap.get("return_code");
			String resultCode = (String) callBackMap.get("result_code");
			String imgurl = "";
			if ("SUCCESS".equals(returnCode) && "SUCCESS".equals(resultCode)) {
				imgurl = (String) callBackMap.get("code_url");
			}
			TwoDimensionCodeUtil dimenUtil=new TwoDimensionCodeUtil();
			response.setHeader("content-disposition", "attachment;filename="+new Date().getTime()+".png");
			ServletOutputStream outputStream = response.getOutputStream();
//			dimenUtil.encoderQRCode(imgurl, outputStream);
			dimenUtil.encoderQRCode(imgurl, outputStream);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	@RequestMapping("getDimenPayImage")
	@ResponseBody
	public Map<String,Object> getDimenPayImage(){
		 Map<String,Object> map= new HashMap<String,Object>();
		 map.put("imageUrl","http://127.0.0.1:9580/shop/scanCode/dimenImage.action");
		return map;
	}
}
